﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using blogDemo.Models;
using PagedList;

namespace blogDemo.Controllers
{
    public class articController : Controller
    {
        private blogDemoDbContext db = new blogDemoDbContext();

        //
        // GET: /artic/

        public ActionResult blog(int? page)
        {
            int pageNumber = page ?? 1;
            int pageSize = 5;
            //Skip之前必须orderby
            var artics = (from a in db.artics
                          orderby a.ID descending
                          select a);

            ViewBag.labels = (from l in db.artics
                          select l.label).Distinct().ToList();

            ViewBag.mostViewed = (from a in db.artics
                                  orderby a.views descending
                                  select a).Take(3);

            ViewBag.recent = (from a in db.artics
                              orderby a.date descending
                              select a).Take(3);

            return View(artics.ToPagedList(pageNumber, pageSize));
        }

        //
        // GET: /artic/

        public ActionResult home()
        {
            return View();
        }

        //
        // GET: /artic/Details/5

        public ActionResult Details(int id = 0)
        {
            artic artic = db.artics.Find(id);
            if (artic == null)
            {
                return HttpNotFound();
            }
            else
            {
                artic.views += 1;
                db.SaveChanges();
            }
            return View(artic);
        }

        //
        // GET: /artic/Detail/5

        public ActionResult Detail(int id = 0)
        {
            artic artic = db.artics.Find(id);
            if (artic == null)
            {
                return HttpNotFound();
            }
            else
            {
                artic.views += 1;
                db.SaveChanges();
            }
            return View(artic);
        }

        //
        // GET: /artic/Search

        public ActionResult Search(string keyword,int? page)
        {
            int pageNumber = page ?? 1;
            int pageSize = 5;

            var artics = db.artics.Where(a => (a.label.Contains(keyword)) || (a.title.Contains(keyword))).OrderByDescending(a => a.date);

            return View(artics.ToPagedList(pageNumber, pageSize));
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}